package cn.stylefeng.guns.modular.basic.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.QRCodeUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicGoods;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.params.DictParam;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 商品表控制器
 */
@Controller
@RequestMapping("/basicGoods")
public class BasicGoodsController extends BaseController {

    private String PREFIX = "/basic/basicGoods";

    @Autowired
    private BasicGoodsService basicGoodsService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;

    /**
     * 跳转到主页面
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/basicGoods.html";
    }

    /**
     * 去批量打印页面
     */
    @RequestMapping("/tobtnqrCode")
    public String tobtnqrCode() {
        return PREFIX + "/btnqrCode.html";
    }

    /**
     * 创建二维码
     */
    @RequestMapping(value = "/getqrcode", method = RequestMethod.GET)
    @ResponseBody
    public void generateQRCode4Product(String id,String name, HttpServletRequest request, HttpServletResponse response) {
        try {
            //logo
            File logoFile = new File("");
            String url = id;
            QRCodeUtil.drawLogoCode_128(logoFile, url, name,600,350,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出Excel
     */
    @RequestMapping("/exportExcelBySpec")
    public void exportExcelBySpec(HttpServletResponse response, BasicGoodsParam basicGoodsParam) throws IOException {
        Workbook wb = basicGoodsService.exportToExcel(basicGoodsParam);
        OutputStream output = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Product Information" + ".xlsx").getBytes(), "iso-8859-1"));
        wb.write(output);
        output.close();
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/import.html";
    }

    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/goods.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Product Template" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入excel
     */
	@RequestMapping(value = "/importExcel" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file,  BasicGoodsParam basicGoodsParam)  {
		ResponseData data = new ResponseData();
        Object goodsCustomerId = basicGoodsParam.getGoodsCustomerId();
        if (goodsCustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(goodsCustomerId.toString()));
            basicGoodsParam.setGoodsCustomerName(basicCustomer.getCustomerName());
        }
        User user = userService.getcurrentUser();
		basicGoodsParam.setDeliverId(user.getDeliverId());
		basicGoodsParam.setDeptId(user.getDeptId());
		try {
			data = basicGoodsService.getExceldata(file,basicGoodsParam,data);//处理导入数据
		} catch (Exception e) {
			data.setSuccess(false);
			e.printStackTrace();
		}
        return data;
    }

    /**
     * 导入更新页面
     */
    @RequestMapping("/toimportExcelUpdate")
    public String toimportExcelUpdate(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/importUpdate.html";
    }

    /**
     * 导入更新excel
     */
	@RequestMapping(value = "/importExcelUpate" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExcelUpate(@RequestPart("file") MultipartFile file,  BasicGoodsParam basicGoodsParam)  {
		ResponseData data = new ResponseData();
        Object goodsCustomerId = basicGoodsParam.getGoodsCustomerId();
        if (goodsCustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(goodsCustomerId.toString()));
            basicGoodsParam.setGoodsCustomerName(basicCustomer.getCustomerName());
        }
		try {
			data = basicGoodsService.getExceldataUpadate(file,basicGoodsParam,data);//处理导入数据
		} catch (Exception e) {
			data.setSuccess(false);
			e.printStackTrace();
		}
        return data;
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add(DictParam dictParam, Model model) {
        perViewData(dictParam,model);
       return PREFIX + "/basicGoods_add.html";
    }

    /**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit(DictParam dictParam,Model model) {
        perViewData(dictParam, model);
        return PREFIX + "/basicGoods_edit.html";
    }

    public void perViewData(DictParam dictParam,Model model){
    	User user = userService.getcurrentUser();
//        //单位COMPANY
//        List<DictResult> dictResultList = dictService.findByDicttypeCode2("COMPANY");
//        model.addAttribute("dictResultList",dictResultList);
//        //包装
//        List<DictResult> dictResultList2 = dictService.findByDicttypeCode2("PACKAGE");
//        model.addAttribute("dictResultList2",dictResultList2);
//        // 商品大类COMMODITY_CATEGORY
//        List<DictResult> dictResultList3 = dictService.findByDicttypeCode2("COMMODITY_CATEGORY");
//        model.addAttribute("dictResultList3",dictResultList3);

    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
    }

    /**
     * 查询商品大类下的商品类别
     * @param goodsBigType
     * @return
     */
    @RequestMapping("/cascade")
    @ResponseBody
    public List<DictResult> cascade(Long  goodsBigType) {
        List<DictResult> dictResults = dictService.findByDictId(goodsBigType);
        return  dictResults;
    }

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BasicGoodsParam basicGoodsParam) {
        Object goodsCustomerId = basicGoodsParam.getGoodsCustomerId();
        if (goodsCustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(goodsCustomerId.toString()));
            basicGoodsParam.setGoodsCustomerName(basicCustomer.getCustomerName());
        }
        if(basicGoodsParam!=null){
        	String goodsName = basicGoodsParam.getGoodsName();
        	//解决参数中的 英文括号
        	if (goodsName!=null&&goodsName!="") {
        		goodsName = goodsName.replace("& #40;", "(");
        		goodsName = goodsName.replace("& #41;", ")");
            	basicGoodsParam.setGoodsName(goodsName);
        	}
        }

        User user = userService.getcurrentUser();
        basicGoodsParam.setDeliverId(user.getDeliverId());
        basicGoodsParam.setDeptId(user.getDeptId());

        BasicGoodsParam param = new BasicGoodsParam();
        param.setGoodsCustomerId(basicGoodsParam.getGoodsCustomerId());
        param.setGoodsNumber(basicGoodsParam.getGoodsNumber());
        BasicGoodsResult result = basicGoodsService.findBySpec(param,null);
        if(result != null) {
        	return ResponseData.error("The product number already exists");
        }

        this.basicGoodsService.add(basicGoodsParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BasicGoodsParam basicGoodsParam) {
        Object goodsCustomerId = basicGoodsParam.getGoodsCustomerId();
        if (goodsCustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(goodsCustomerId.toString()));
            basicGoodsParam.setGoodsCustomerName(basicCustomer.getCustomerName());
        }
        if(basicGoodsParam!=null){
        	String goodsName = basicGoodsParam.getGoodsName();
        	//解决参数中的 英文括号
        	if (goodsName!=null&&goodsName!="") {
        		goodsName = goodsName.replace("& #40;", "(");
        		goodsName = goodsName.replace("& #41;", ")");
            	basicGoodsParam.setGoodsName(goodsName);
        	}
        }

        BasicGoodsParam param = new BasicGoodsParam();
        param.setId(basicGoodsParam.getId());
        param.setGoodsCustomerId(basicGoodsParam.getGoodsCustomerId());
        param.setGoodsNumber(basicGoodsParam.getGoodsNumber());
        BasicGoodsResult result = basicGoodsService.findBySpec(param,null);
        if(result != null) {
        	return ResponseData.error("The product number already exists");
        }

        this.basicGoodsService.update(basicGoodsParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BasicGoodsParam basicGoodsParam) {
        this.basicGoodsService.delete(basicGoodsParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BasicGoodsParam basicGoodsParam) {
        BasicGoods detail = this.basicGoodsService.getById(basicGoodsParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BasicGoodsParam basicGoodsParam,String condition ) {
    	User user = userService.getcurrentUser();
        basicGoodsParam.setDeliverId(user.getDeliverId());
        if (condition!=null&&condition!="") {
            condition = condition.replace("& #40;", "(");
            condition = condition.replace("& #41;", ")");
        }
        return this.basicGoodsService.findPageBySpec(basicGoodsParam,condition,user.getDeptId(),user.getOperateId());
    }

    /**
     * 跳转到拉取商鼎新商品页面
     */
    @RequestMapping("topullSd")
    public String topullSd(Model model) {
    	User user = userService.getcurrentUser();
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/pullSd.html";
    }

    /**
     * 拉取商鼎新商品
     */
    @ResponseBody
    @RequestMapping("/getSd")
    public ResponseData getSd(BasicGoodsParam basicGoodsParam,String modified_begin,String modified_end) {
    	if (ToolUtil.isNotEmpty(modified_begin) && ToolUtil.isNotEmpty(modified_end)) {
    		basicGoodsParam.setNewDate("'"+modified_begin+"' and '"+modified_end+"'");
		}
    	List<BasicGoodsResult> list = basicGoodsService.findListBySpecSd(basicGoodsParam);
        return ResponseData.success();
    }

}


